/**
 * 
 */
package com.suixun.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.authority.controller.BaseManager;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.suixun.Result;
import com.suixun.entity.DeviceInfo;
import com.suixun.entity.LogOperation;
import com.suixun.entity.form.ParamForm;
import com.suixun.enums.APICode;
import com.suixun.service.DeviceService;
import com.suixun.service.impl.DeviceServiceImpl;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;
import com.suixun.util.ExcelUtil;
import com.suixun.vo.ChangeDeviceVo;
import com.suixun.vo.DeviceVO;
import com.suixun.vo.UnbindDeviceVo;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/deviceManage")
public class DeviceManage extends BaseManager {
	@Resource
	private DeviceService deviceService;

	/**
	 * 查询所有设备列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "queryDevice.json")
	@ResponseBody
	public Object queryDevice(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (paramForm == null) {
				return fail(Constant.EMPTY);
			}
			return success(deviceService.queryDevice(paramForm));
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceManage queryDevice:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 分页查询设备列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "queryDeviceList.json")
	@ResponseBody
	public Object queryDeviceListPage(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			return success(deviceService.queryDevicelistPage(paramForm));
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceManage queryDeviceListPage:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 导出excel，不做鉴权
	 * 
	 * @return
	 */

	@RequestMapping(value = "export_DeviceList.json")
	@ResponseBody
	public Object exportDeviceList(String param) {
		boolean bln = checkRight();
		if (!bln) {
			toRedirect(404);
		}

		try {
			ParamForm paramForm = null;
			if (param == null) {
				paramForm = new ParamForm();
			} else {
				paramForm = new Gson().fromJson(param, ParamForm.class);
			}
			paramForm.setIsExport("true");
			// 创建新的Excel 工作簿
			HSSFWorkbook workbook = deviceService.exportDeviceList(paramForm);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=devicelist.xls");
			workbook.write(this.getResponse().getOutputStream());
			workbook.close();
			return success();
		} catch (Exception e) {
			logger("DeviceManage exportDeviceList:" + e.getMessage(), e);
			toRedirect(500);
		}
		return success();

	}

	/**
	 * 设备回收
	 * 
	 * @return
	 */

	@RequestMapping(value = "recycleDevice.json")
	@ResponseBody
	public Object recycleDevice(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (paramForm == null || StringUtil.isBlank(paramForm.getImei())) {
				return fail(Constant.EMPTY);
			}
			int successCount = 0; // 回收成功的数量
			int failCount = 0; // 回收失败的数量
			String failImei = ""; // 回收失败的设备号码
			String[] imeilist = paramForm.getImei().split("[|]");
			for (int i = 0; i < imeilist.length; i++) {
				int res = deviceService.recycleDevice(imeilist[i]);
				if (res == 1) {
					successCount++;
				} else {
					failCount++;
					failImei += imeilist[i] + ",";
				}
			}
			if (successCount == 0) {
				return fail(Constant.OPERATE_FAIL);
			} else {
				HashMap<String, String> result = new HashMap<String, String>();
				result.put("resultstatus", failCount == 0 ? "1" : "3");
				result.put("resultinfo",
						failCount == 0 ? Constant.Device.RECYLE_TRUE : Constant.Device.RECYLE_PART_TRUE);
				result.put("failimei", failImei);
				return success(result);
			}
		} catch (Exception e) {
			logger("DeviceManage recycleDevice:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * <p>
	 * Title: recycleToReserve
	 * </p>
	 * <p>
	 * 功能描述:回收到储备量
	 * </p>
	 * 
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/recycleToReserve.json")
	@ResponseBody
	public Object recycleToReserve(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (com.suixun.util.StringUtil.isEmpty(param)) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (paramForm == null || StringUtil.isBlank(paramForm.getImei())) {
				return fail(Constant.IMEI_NOT_NULL);
			}
			if (StringUtil.isBlank(paramForm.getProvince()) || StringUtil.isBlank(paramForm.getCity())
					|| StringUtil.isBlank(paramForm.getTown())) {
				return fail(Constant.REGION_NOT_NULL);
			}
			String recycle = deviceService.recycleToReserve(paramForm.getImei(), paramForm.getProvince(),
					paramForm.getCity(), paramForm.getTown());
			if (Constant.SUCCESS.equals(recycle)) {
				return success();
			} else {
				return success(recycle);
			}
		} catch (Exception e) {
			if (e.getMessage().contains("学生证") || e.getMessage().contains("设备")) {
				return fail(e.getMessage());
			}
			logger("DeviceManage recycleToReserve:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 修改设备
	 * 
	 * @return
	 */

	@RequestMapping(value = "modifyDevicePhone.json")
	@ResponseBody
	public Object modifyDevicePhone(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			DeviceInfo deviceInfo = new Gson().fromJson(param, DeviceInfo.class);
			if (deviceInfo == null || StringUtil.isBlank(deviceInfo.getMdtid())) {
				return fail(Constant.EMPTY);
			}
			ParamForm form = new ParamForm();
			form.setImei(deviceInfo.getMdtid());
			List<DeviceVO> list = deviceService.queryDevice(form);
			String modifyType = deviceInfo.getModifytype() != null ? deviceInfo.getModifytype() : "";
			LogOperation logOperation = new LogOperation();
			logOperation.setMdtid(deviceInfo.getMdtid());
			logOperation.setOperationerid(String.valueOf(getUserId()));
			logOperation.setOperationername(getUsername());

			if (modifyType.equals("1")) {
				if (list.size() == 1) {
					logOperation.setOldvalue(list.get(0).getTelephone());
				}
				logOperation.setOperation(",modifyDevicePhone");
				logOperation.setNewvalue(deviceInfo.getTelephone());
				deviceService.addLogOperation(logOperation);
				deviceService.modifyDevicePhone(deviceInfo);
				return success();
			} else if (modifyType.equals("2")) {
				if (list.size() == 1) {
					logOperation.setOldvalue(list.get(0).getCardid());
				}
				if (deviceInfo.getMdtid().startsWith(Constant._13_56_MDTID_PREFIX)
						|| deviceInfo.getMdtid().startsWith(Constant._2_4G_MDTID_PREFIX)) {
					logOperation.setMdtid(new StringBuffer().append(deviceInfo.getMdtid().substring(0, 4))
							.append(deviceInfo.getCardid()).toString());
				}
				logOperation.setOperation(",modifyCardId");
				logOperation.setNewvalue(deviceInfo.getCardid());
				deviceService.addLogOperation(logOperation);
				int result = deviceService.modifyCardId(deviceInfo);
				if (result == -1) {
					return fail(Constant.Device.CARDID_IS_EXIST);
				}
				return success();
			} else if (modifyType.equals("3")) {
				if (list.size() == 1) {
					logOperation.setOldvalue(list.get(0).getEndtime());
				}
				if (StringUtils.isBlank(deviceInfo.getEndtimestring())) {
					return fail("设备有效期不能为空");
				}
				deviceInfo
						.setEndtime(DateUtil.formatStringToTime(deviceInfo.getEndtimestring(), "yyyy-MM-dd HH:mm:ss"));
				logOperation.setOperation(",modifyEndTime");
				logOperation.setNewvalue(DateUtil.formatDateToString(deviceInfo.getEndtime(), null));
				deviceService.addLogOperation(logOperation);
				int result = deviceService.modifyEndTime(deviceInfo);
				if (result == -1) {
					return fail("设备号不符");
				} else if (result == -2) {
					return fail("不能修改考勤卡的有效期");
				}
				return success();
			} else
				return fail(Constant.OPERATE_FAIL);

		} catch (Exception e) {
			logger("DeviceManage modifyDevicePhone:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 分页查询设备修改历史
	 * 
	 * @return
	 */

	@RequestMapping(value = "queryDeviceHistory.json")
	@ResponseBody
	public Object queryDeviceHistory(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (paramForm == null || paramForm.getImei() == null || paramForm.getImei().trim().equals("")) {
				return fail(Constant.EMPTY);
			}
			return success(deviceService.queryDeviceHistoryPage(paramForm));
		} catch (Exception e) {
			logger("DeviceManage queryDeviceHistory:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}

	/**
	 * 
	 * <p>
	 * Title: unbindDevice
	 * </p>
	 * <p>
	 * 功能描述:解绑设备
	 * </p>
	 * 
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "unbindDevice.json")
	public Object unbindDevice(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (StringUtils.isEmpty(paramForm.getImei()) || StringUtils.isEmpty(paramForm.getObjectid())
					|| StringUtils.isEmpty(paramForm.getPeopleid())) {
				return fail(Constant.EMPTY);
			}
			Integer isbind = deviceService.unbindDevice(paramForm);
			if (isbind == -1) {
				return fail(Constant.Device.DEVICE_IS_PAY);
			} else if (isbind == -2) {
				return fail(Constant.Device.IMEI_FALSE);
			} else {
				return success(Constant.OPERATE_SUCCESS);
			}
		} catch (Exception e) {
			logger("DeviceManage unbindDevice:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}

	/**
	 * excel导入解绑多个设备
	 * 
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "unbindManyDevice.json")
	public Object unbindManyDevice(@RequestParam("file") MultipartFile file) {
		if (!checkRight()) {
			return fail(Constant.Authority.CHECK_FALSE);
		}

		try {
			Workbook wb = createWorkbook(file);
			if (wb == null) {
				return fail("请上传正确的excel文件");
			}

			Map<String, String> tableMap = new HashMap<>();
			tableMap.put(UnbindDeviceVo.HEADER1[1], UnbindDeviceVo.HEADER1[0]);
			tableMap.put(UnbindDeviceVo.HEADER2[1], UnbindDeviceVo.HEADER2[0]);

			List<UnbindDeviceVo> unbindDeviceVo = new ExcelUtil().getExcelValue(tableMap, wb, UnbindDeviceVo.class);

			deviceService.unbindManyDevice(unbindDeviceVo);

			return success(Constant.OPERATE_SUCCESS);
		} catch (Exception e) {
			logger("DeviceManage unbindManyDevice:" + e.getMessage(), e);
			if (e.getCause() != null) {
				return fail(unbindChangeDeviceFail(e.getCause()));
			}
			return fail(unbindChangeDeviceFail(e));
		}
	}

	/**
	 * excel导入批量解绑设备和批量跟换考勤卡的异常数据的返回处理
	 * 
	 * @param e
	 * @return
	 */
	private String unbindChangeDeviceFail(Throwable e) {
		String message = e.getMessage();
		String fileName = e.getStackTrace()[0].getFileName();
		if (fileName.startsWith(ChangeDeviceVo.class.getSimpleName())
				|| fileName.startsWith(UnbindDeviceVo.class.getSimpleName())) {
			return message;
		} else if (fileName.startsWith(DeviceServiceImpl.class.getSimpleName())) {
			String[] msgs = message.split(",");
			if (msgs.length < 2) {
				return message;
			} else {
				String str = msgs[1];
				if (Integer.parseInt(msgs[0]) == -1) {
					return Constant.Device.DEVICE_IS_PAY + str;
				} else if (Integer.parseInt(msgs[0]) == -2) {
					return Constant.Device.IMEI_FALSE + str;
				}
			}
		}
		return Constant.EXCEPTION.OPERATE_FAIL;
	}

	/**
	 * 根据文件创建Workbook
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private Workbook createWorkbook(MultipartFile file) throws IOException {
		Workbook wb = null;
		String fileName = file.getOriginalFilename();
		if (fileName.endsWith("xls")) {
			wb = new HSSFWorkbook(file.getInputStream());
		} else if (fileName.endsWith("xlsx")) {
			wb = new XSSFWorkbook(file.getInputStream());
		}
		return wb;
	}

	/**
	 * 下载批量解绑模板
	 * 
	 * @return
	 */
	@RequestMapping(value = "/unbindManyTamplate", method = RequestMethod.GET)
	@ResponseBody
	public Object unbindManyTamplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook = null;
			List<List<String>> listValue = new LinkedList<List<String>>();
			listParm.add(UnbindDeviceVo.HEADER1[0]);
			listParm.add(UnbindDeviceVo.HEADER2[0]);
			listExample.add("14位考勤卡号");
			listExample.add("主监护人手机号");
			listExample.add(Constant.Excel.WARNING);
			// 创建新的Excel 工作簿
			workbook = exportDeviceList("批量解绑考勤卡模板", listParm, listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=unbindManyTamplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("DeviceManage unbindManyTamplate:" + e.getMessage(), e);
			toRedirect(500);
		}
		return success();
	}

	/**
	 * excel导入跟换多个考勤卡
	 * 
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "changeDevice.json")
	public Object changeDevice(@RequestParam("file") MultipartFile file) {
		if (!checkRight()) {
			return fail(Constant.Authority.CHECK_FALSE);
		}

		try {
			Workbook wb = createWorkbook(file);
			if (wb == null) {
				return fail("请上传正确的excel文件");
			}

			Map<String, String> tableMap = new HashMap<>();
			tableMap.put(ChangeDeviceVo.HEADER1[1], ChangeDeviceVo.HEADER1[0]);
			tableMap.put(ChangeDeviceVo.HEADER2[1], ChangeDeviceVo.HEADER2[0]);
			tableMap.put(ChangeDeviceVo.HEADER3[1], ChangeDeviceVo.HEADER3[0]);
			tableMap.put(ChangeDeviceVo.HEADER4[1], ChangeDeviceVo.HEADER4[0]);
			List<ChangeDeviceVo> changeDeviceVo = new ExcelUtil().getExcelValue(tableMap, wb, ChangeDeviceVo.class);

			if (!verifyCard(changeDeviceVo)) {
				return fail("考勤卡号有重复!");
			}

			deviceService.changeDevice(changeDeviceVo);
			return success(Constant.OPERATE_SUCCESS);
		} catch (Exception e) {
			logger("DeviceManage changeDevice:" + e.getMessage(), e);
			if (e.getCause() != null) {
				return fail(unbindChangeDeviceFail(e.getCause()));
			}
			return fail(unbindChangeDeviceFail(e));
		}
	}

	/**
	 * 单个跟换考勤卡
	 * 
	 * @param oldCardid
	 *            旧卡cardid
	 * @param oldType
	 *            旧卡类型
	 * @param newCardid
	 *            新卡cardid
	 * @param newType
	 *            旧卡类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "singleChangeDevice.json")
	public Object singleChangeDevice(@RequestParam("oldCardid") String oldCardid,
			@RequestParam("oldType") String oldType, @RequestParam("newCardid") String newCardid,
			@RequestParam("newType") String newType) {
		if (!checkRight()) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			ChangeDeviceVo vo = new ChangeDeviceVo();
			vo.setOldCardid(oldCardid);
			vo.setOldType(oldType);
			vo.setNewCardid(newCardid);
			vo.setNewType(newType);

			deviceService.changeDevice(Lists.newArrayList(vo));
			return success(Constant.OPERATE_SUCCESS);
		} catch (Exception e) {
			logger("DeviceManage singleChangeDevice:" + e.getMessage(), e);
			if (e.getCause() != null) {
				return fail(unbindChangeDeviceFail(e.getCause()));
			}
			return fail(unbindChangeDeviceFail(e));
		}
	}

	/**
	 * 校验批量考勤卡号的唯一性
	 * 
	 * @param list
	 * @return
	 */
	private boolean verifyCard(List<ChangeDeviceVo> list) {
		if (CollectionUtils.isNotEmpty(list)) {
			Set<String> set = Sets.newHashSet();
			for (int i = 0; i < list.size(); i++) {
				set.add(list.get(i).getProtoOldCardid());
				set.add(list.get(i).getProtoNewCardid());
			}
			if (set.size() != list.size() * 2) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 下载批量更换考勤卡模板
	 * 
	 * @return
	 */
	@RequestMapping(value = "/changeDeviceTamplate", method = RequestMethod.GET)
	@ResponseBody
	public Object changeDeviceTamplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook = null;
			List<List<String>> listValue = new LinkedList<List<String>>();
			listParm.add(ChangeDeviceVo.HEADER1[0]);
			listParm.add(ChangeDeviceVo.HEADER2[0]);
			listParm.add(ChangeDeviceVo.HEADER3[0]);
			listParm.add(ChangeDeviceVo.HEADER4[0]);
			listExample.add("10位考勤卡号");
			listExample.add("2.4/13.56");
			listExample.add("10位考勤卡号");
			listExample.add("2.4/13.56");
			listExample.add(Constant.Excel.WARNING);
			// 创建新的Excel 工作簿
			workbook = exportDeviceList("批量更换考勤卡模板", listParm, listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=changeDeviceTamplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("DeviceManage changeDeviceTamplate:" + e.getMessage(), e);
			toRedirect(500);
		}
		return success();
	}

	@RequestMapping(value = "/batchActivateCard.json", method = RequestMethod.POST)
	@ResponseBody
	public Object batchActivateCard(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

		InputStream fileReport = null;
		try {
			fileReport = file.getInputStream();
			String fileName = file.getOriginalFilename();
			Workbook wb = null;
			if (fileName.endsWith("xls")) {
				wb = new HSSFWorkbook(fileReport);
			} else if (fileName.endsWith("xlsx")) {
				wb = new XSSFWorkbook(fileReport);
			} else {
				return fail("请上传正确的excel文件");
			}
			String result = deviceService.batchAddStudent(wb);
			if (result != null) {
				return fail(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceManage batchActivateCard:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
		return success();
	}

	@RequestMapping(value = "/export_batchActivateCardTamplate.json")
	@ResponseBody
	public Object exportTamplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook = null;
			List<List<String>> listValue = new LinkedList<List<String>>();
			listParm.add("考勤卡号");
			listParm.add("学生姓名");
			listParm.add("班主任手机号");
			listParm.add("用户手机号");
			listParm.add("是否是主监护人");
			listParm.add("主监护人手机号");
			listExample.add("123456780");
			listExample.add("必填");
			listExample.add("必填");
			listExample.add("必填");
			listExample.add("是/否 (默认为是)");
			listExample.add("添加普通监护人时必填");
			listExample.add(Constant.Excel.WARNING);
			// 创建新的Excel 工作簿
			workbook = exportDeviceList("批量激活考勤卡模板", listParm, listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=batchActivateCardTamplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("DeviceManage export_batchActivateCardTamplate:" + e.getMessage(), e);
			toRedirect(500);
		}
		return success();
	}

	@ResponseBody
	@RequestMapping(value = "synJxtBaby.json")
	public Object synJxtBaby(String param) {
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (StringUtils.isEmpty(paramForm.getImei())) {
				return fail(Constant.EMPTY);
			}
			String res = deviceService.synJxtBaby(paramForm.getImei());
			if (res != null) {
				return fail(res);
			}
			return success();
		} catch (Exception e) {
			logger("DeviceManage synJxtBaby:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}

	/**
	 * 导出批量为已有学生证且没有绑定有效考勤卡的学生绑定考勤卡的模板Excel表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportbatchbindwhitecardTemplate.json")
	@ResponseBody
	public Object exportbatchbindwhitecardTemplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook = null;
			String[] labels = { "学生姓名", "家长手机号", "学生证mdtid", "考勤卡mdtid" };
			for (String label : labels) {
				listParm.add(label);
			}
			List<List<String>> listValue = new LinkedList<List<String>>();
			// 创建新的Excel 工作簿
			workbook = exportDeviceList("批量绑定考勤卡", listParm, listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=exportbatchbindwhitecardTemplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("TeacherController exportbatchbindwhitecardTemplate:" + e.getMessage(), e);
			toRedirect(500);
		}
		return success();
	}

	/**
	 * 
	 * 批量为已有学生证学生绑定考勤卡
	 * 
	 * @return
	 */
	@RequestMapping(value = "/bindwhitecardBatch.json", method = RequestMethod.POST)
	@ResponseBody
	public Object bindwhitecardBatch(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		// boolean bln=checkRight();
		// if(!bln) {
		// return fail(Constant.Authority.CHECK_FALSE);
		// }
		InputStream fileReport = null;
		try {
			fileReport = file.getInputStream();
			String fileName = file.getOriginalFilename();
			// 1.Excel是否都不为空或者有效数据
			if (fileName.endsWith("xlsx")) {
				return fail(Constant.Excel.TYPE_IS_FALSE);
			}
			// 把一张xls的数据表读到wb里
			HSSFWorkbook wb = new HSSFWorkbook(fileReport);
			// 批量修改手机
			Object result = deviceService.bindwhitecardBatch(wb);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger("TeacherController addTeachers:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		} finally {
			try {
				fileReport.close();
			} catch (IOException e) {
				logger("TeacherController addTeachers:" + e.getMessage(), e);
			}
		}
	}

	/**
	 * 
	 * @param pageno
	 * @param pagesize
	 * @param type
	 *            类别 0 ：所有1：已注销，2：未注销 3 ：未注销，但是超过哦5天
	 * @param devicetype
	 *            0:所有 设备类型 2-学生证，3 考勤卡
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getlostreportdevice.json")
	@ResponseBody
	public Object getlostreportdevice(String pageno, String pagesize, String type, Integer devicetype,
			HttpServletRequest request) {
		// boolean bln=checkRight();
		// if(!bln) {
		// return fail(Constant.Authority.CHECK_FALSE);
		// }
		int pagenoint = 1;
		int pagesizeint = 20;
		int typeint = 0;
		if (devicetype == null || (devicetype != 1 && devicetype != 2 && devicetype != 3)) {
			devicetype = 0;
		}
		if (StringUtils.isEmpty(pageno)) {
			pageno = 1 + "";
		}
		try {
			pagenoint = Integer.parseInt(pageno);
			pagesizeint = Integer.parseInt(pagesize);
			typeint = Integer.parseInt(type);
		} catch (Exception e) {
			// TODO: handle exception
		}

		Object result = deviceService.getlostreportdevice(pagenoint, pagesizeint, devicetype, typeint);
		return result;
	}

	/**
	 * 导出各种挂失设备
	 * 
	 * @param flag
	 *            1导出挂失日期超过15天的学生证,并且未注销的 2所有挂失中的设备 3挂失超过15天且未注销的考勤卡
	 * @return
	 */
	@RequestMapping(value = "/exportlostreportdevicelist.json")
	@ResponseBody
	public Result exportlostreportdevicelist(String type) {
		// 权限验证

		if (StringUtils.isEmpty(type)) {
			return new Result(APICode.FAIL.setCustomMsg("操作类型为空"), null);
		}

		int typeint = 1;
		try {
			typeint = Integer.parseInt(type);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Result result = deviceService.exportlostreportdevicelist(typeint, this);
		return result;
	}

	/**
	 * 此接口没有使用 导出批量解除考勤卡操作的模板
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportbatchunbindwhitecardTemplate.json")
	@ResponseBody
	public Object exportbatchunbindwhitecardTemplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook = null;
			String[] labels = { "学生姓名", "家长手机号", "考勤卡mdtid", "设备类型(2：智能学生证；31：13.56G考勤卡；32：2.4G考勤卡)" };
			for (String label : labels) {
				listParm.add(label);
			}
			List<List<String>> listValue = new LinkedList<List<String>>();
			// 创建新的Excel 工作簿
			workbook = exportDeviceList("批量解除考勤卡操", listParm, listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=exportbatchbindwhitecardTemplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("TeacherController exportbatchunbindwhitecardTemplate:" + e.getMessage(), e);
			toRedirect(500);
		}
		return success();
	}

	/**
	 * 此接口没有使用 批量解除考勤卡
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/unbindwhitecardBatch.json", method = RequestMethod.POST)
	@ResponseBody
	public Result unbindwhitecardBatch(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		// boolean bln=checkRight();
		// if(!bln) {
		// return fail(Constant.Authority.CHECK_FALSE);
		// }
		InputStream fileReport = null;
		try {
			fileReport = file.getInputStream();
			String fileName = file.getOriginalFilename();
			// 1.Excel是否都不为空或者有效数据
			if (fileName.endsWith("xlsx")) {
				// return fail(Constant.Excel.TYPE_IS_FALSE);
				return new Result(APICode.FAIL.setCustomMsg(Constant.Excel.TYPE_IS_FALSE), null);
			}
			// 把一张xls的数据表读到wb里
			HSSFWorkbook wb = new HSSFWorkbook(fileReport);
			// 批量修改手机

			// Object result =changePeopleTel(wb);
			Result result = deviceService.unbindwhitecardBatch(wb);
			return result;

			/*
			 * Object isImport=peopleService.importTeachers(wb); if (isImport
			 * instanceof String) { String res = (String)isImport; if
			 * (Constant.SUCCESS.equals(res)) { return success(); }else{ return
			 * fail(res); } }else { return success(isImport); }
			 */
		} catch (Exception e) {
			e.printStackTrace();
			logger("TeacherController addTeachers:" + e.getMessage(), e);
			// return fail(Constant.EXCEPTION.OPERATE_FAIL);
			return new Result(APICode.FAIL.setCustomMsg(Constant.EXCEPTION.OPERATE_FAIL), null);
		} finally {
			try {
				fileReport.close();
			} catch (IOException e) {
				logger("TeacherController addTeachers:" + e.getMessage(), e);
			}
		}
	}

	/**
	 * 此接口没有使用 导出批量更换考勤卡 模板 考勤卡更换考勤卡
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportbatchangewhitecardTemplate.json")
	@ResponseBody
	public Object exportbatchangewhitecardTemplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook = null;
			String[] labels = { "学生姓名", "家长手机号", /* "原考勤卡号mdtid", */"新考勤卡号mdtid", "新设备类型(31：13.56G考勤卡；32：2.4G考勤卡)" };
			for (String label : labels) {
				listParm.add(label);
			}
			List<List<String>> listValue = new LinkedList<List<String>>();
			// 创建新的Excel 工作簿
			workbook = exportDeviceList("批量更换考勤卡 ", listParm, listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=exportbatchbindwhitecardTemplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("TeacherController exportbatchangewhitecardTemplate:" + e.getMessage(), e);
			toRedirect(500);
		}
		return success();
	}

	/**
	 * 此接口没有使用 批量更换考勤卡
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/changewhitecardBatch.json", method = RequestMethod.POST)
	@ResponseBody
	public Result changewhitecardBatch(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		// boolean bln=checkRight();
		// if(!bln) {
		// return fail(Constant.Authority.CHECK_FALSE);
		// }
		InputStream fileReport = null;
		try {
			fileReport = file.getInputStream();
			String fileName = file.getOriginalFilename();
			// 1.Excel是否都不为空或者有效数据
			if (!fileName.endsWith("xls")) {
				return new Result(APICode.FAIL.setCustomMsg(Constant.Excel.TYPE_IS_FALSE), null);
			}
			// 把一张xls的数据表读到wb里
			HSSFWorkbook wb = new HSSFWorkbook(fileReport);
			// 批量修改手机

			Result result = deviceService.changewhitecardBatch(wb);
			return result;

		} catch (Exception e) {
			e.printStackTrace();
			logger("TeacherController addTeachers:" + e.getMessage(), e);
			return new Result(APICode.FAIL.setCustomMsg(Constant.EXCEPTION.OPERATE_FAIL), null);
		} finally {
			try {
				fileReport.close();
			} catch (IOException e) {
				logger("TeacherController addTeachers:" + e.getMessage(), e);
			}
		}
	}

	@RequestMapping(value = "queryDevicesByPeopletel.json")
	@ResponseBody
	public Object queryDevicesByPeopletel(String param) {
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (paramForm == null || paramForm.getPeopletel() == null || paramForm.getPeopletel().trim().equals("")) {
				return fail(Constant.EMPTY);
			}
			return success(deviceService.getDeviceListByPeopletel(paramForm.getPeopletel()));
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceManage queryDevicesByPeopletel:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}

	/**
	 * 批量注销设备，包括学生证和考勤卡
	 * 
	 * @param lostreportids
	 * @return
	 */
	@RequestMapping(value = "logoffafterlost.json")
	@ResponseBody
	public Result logoffafterlost(String lostreportids/* ,String mdtids */) {
		// boolean bln=checkRight();
		// if(!bln) {
		// return fail(Constant.Authority.CHECK_FALSE);
		// }
		if (StringUtils
				.isEmpty(lostreportids)/* ||StringUtils.isEmpty(mdtids) */) {
			return new Result(APICode.FAIL.setCustomMsg("请选择你要注销的设备。"), null);
		}
		lostreportids = lostreportids.replaceAll(" ", "");
		// mdtids = mdtids.replaceAll(" ", "");
		if (lostreportids.length() == 1 /* ||mdtids.length() == 1 */) {
			return new Result(APICode.FAIL.setCustomMsg("请选择你要注销的设备。"), null);
		}
		return deviceService.logoffafterlost(lostreportids/* ,mdtids */);
	}

	@RequestMapping(value = "getlostinfobymdtid")
	@ResponseBody
	public Result getlostinfobymdtid(String mdtid) {
		// boolean bln=checkRight();
		// if(!bln) {
		// return fail(Constant.Authority.CHECK_FALSE);
		// }
		if (StringUtils.isEmpty(mdtid) || mdtid.length() < 10) {
			return new Result(APICode.FAIL.setCustomMsg("设备mdtid不能为空或者无效"), null);
		}
		if (mdtid.length() == 15) {
			mdtid = mdtid.substring(0, 14);
		}
		Result result = deviceService.getlostinfobymdtid(mdtid);
		return result;
	}

	/**
	 * <p>
	 * Title: modifyDevicePrice
	 * </p>
	 * <p>
	 * 功能描述: 修改设备价格
	 * </p>
	 * 
	 * @param mdtid
	 * @return
	 */
	@RequestMapping(value = "modifyDevicePrice")
	@ResponseBody
	public Object modifyDevicePrice(String mdtid, String promotePrice, String packagePrice) {
		if (StringUtils.isEmpty(mdtid)) {
			return fail("设备号为空");
		}
		if (mdtid.length() == 15) {
			mdtid = mdtid.substring(0, mdtid.length() - 1);
		}
		if (mdtid.length() != 14) {
			return fail("设备号长度不是14位");
		}
		if (StringUtils.isEmpty(promotePrice)) {
			return fail("推广价为空");
		}
		if (StringUtils.isEmpty(packagePrice)) {
			return fail("套餐价为空");
		}
		String result = deviceService.modifyDevicePrice(mdtid, promotePrice, packagePrice);
		if (result == null) {
			return success();
		} else {
			return fail(result);
		}
	}

	/**
	 * 根据考勤卡id获取设备mdtid和设备类型
	 * 
	 * @param cardid
	 *            勤卡id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "get_mdtid_type")
	public Object getMdtidType(@RequestParam("cardid") String cardid) {
		/*
		 * if (!checkRight()) { return fail(Constant.Authority.CHECK_FALSE); }
		 */
		try {
			if (StringUtils.isEmpty(cardid) || !cardid.matches("^\\d{10}$")) {
				return fail("参数错误");
			}
			return success(deviceService.getMdtidType(cardid));
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceManage queryDevicesByPeopletel:" + e.getMessage(), e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}

	/**
	 * 
	 * 功能描述: 发送指令
	 * 
	 * @param mdtid
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "sendInstructions.json", method = RequestMethod.POST)
	public Object sendInstructions(String mdtid, Integer type) {
		if (type == null) {
			return fail("类型不能为空");
		}
		deviceService.sendInstructions(mdtid, type);
		return success();
	}

	/**
	 * 
	 * 功能描述: 查询本月设备消息列表（通话时长，通信流量）
	 * @param mdtid
	 * @param objectId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "listCurrentMonthMessage.json")
	public Object listCurrentMonthMessage(String mdtid, Integer objectId) {
		if (objectId != null) {
			return success(deviceService.listCurrentMonthMessage(objectId));
		} else if (StringUtils.isNotBlank(mdtid)) {
			return success(deviceService.listCurrentMonthMessage(mdtid));
		} else {
			return success();
		}
	}
	
	/**
	 * 
	 * 功能描述: 查询本月设备消息（通话时长，通信流量）
	 * @param mdtid
	 * @param objectId
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getCurrentMonthMessage.json")
	public Object getCurrentMonthMessage(String mdtid, Integer objectId, Integer type) {
		if(type == null) {
			return fail("类型不能为空");
		}
		if (objectId != null) {
			return success(deviceService.selectCurrentMonthMessage(type, objectId));
		} else if (StringUtils.isNotBlank(mdtid)) {
			return success(deviceService.selectCurrentMonthMessage(type, mdtid));
		} else {
			return success();
		}
	}
}
